package com.kaigejava.topicexchange;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

/**
 * Created by kaigejava on 2019/7/13.
 */
public class Consumer4TopicExchange {
    public static void main(String[] args) throws  Exception{
        //1:创建一个connectioFactory工厂对象，并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置ip 端口 vhost等
        connectionFactory.setHost("192.168.31.129");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        //2：通过工厂对象获取到connection对象
        Connection connection = connectionFactory.newConnection();

        //3：通
        // 过connection对象获取到一个消息通信的通道 channel
        Channel channel = connection.createChannel();
        String exchangeName = "test_topic_exchange";
        String exchangeType = "topic";
        String queueName ="test_topic_queue";
       // String routingKey = "user.#";
        String routingKey = "user.*";
        //4.1 声明交换机
        channel.exchangeDeclare(exchangeName,exchangeType);
        // 4.2 : 声明队列
        channel.queueDeclare(queueName,false,false,false,null);
        //4.3: 建立交换机和队列的绑定关系
        channel.queueBind(queueName,exchangeName,routingKey);

        //
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName,true,consumer);
        while(true){
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String  msg = new String (delivery.getBody());
            System.out.println("topic consumer收到的消息为："+msg);
        }
    }
}
